package com.zxx.flowerstore.service.impl;

import com.zxx.flowerstore.dao.FlowerUserMapper;
import com.zxx.flowerstore.entity.FlowerCodeRule;
import com.zxx.flowerstore.entity.FlowerUser;
import com.zxx.flowerstore.entity.FlowerUserExample;
import com.zxx.flowerstore.entity.constant.MagicConstant;
import com.zxx.flowerstore.entity.enums.CodeRuleEnum;
import com.zxx.flowerstore.entity.enums.ResultEnum;
import com.zxx.flowerstore.service.MailService;
import com.zxx.flowerstore.service.UserService;
import com.zxx.flowerstore.utils.RedisRepository;
import com.zxx.flowerstore.utils.common.GeneratorCodeForMysql;
import com.zxx.flowerstore.utils.common.HighArray;
import com.zxx.flowerstore.utils.common.MyException;
import com.zxx.flowerstore.utils.common.Result;
import com.zxx.flowerstore.utils.utils.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName UserServiceImpl
 * @Author Admin
 * @Date 2021/3/16 20:45
 * @Description UserServiceImpl
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private FlowerUserMapper flowerUserMapper;

    @Autowired
    private GeneratorCodeForMysql generatorCodeForMysql;

    @Autowired
    private RedisRepository redisRepository;

    @Autowired
    private MailService mailService;

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Override
    public Result register(FlowerUser flowerUser) {
        this.checkRegisterInfo(flowerUser);
        try {
            this.createUser(flowerUser);
        } catch (Exception e) {
            return Result.error(ResultEnum.ERROR.getCode(), "注册失败");
        }
        return Result.success();
    }


    @Override
    public Result sendEmailCode(FlowerUser flowerUser) {
        if (StringUtils.isEmpty(flowerUser.getEmail())) {
            return Result.error(ResultEnum.ERROR.getCode(), "请传入邮箱地址");
        }
        FlowerUserExample flowerUserExample = new FlowerUserExample();
        flowerUserExample.createCriteria().andEmailEqualTo(flowerUser.getEmail());
        List<FlowerUser> emailList = flowerUserMapper.selectByExample(flowerUserExample);
        if (!CollectionUtils.isEmpty(emailList)) {
            return Result.error(ResultEnum.ERROR.getCode(), "邮箱已存在,可以直接登录,如果忘记密码,请联系管理员找回密码");
        }
        // 生成验证码并存redis
        String code = HighArray.MobileVfCode();
        logger.info("生成验证码为：" + code);
        redisRepository.set(MagicConstant.getVerificationCode() + flowerUser.getEmail(), code, 30, TimeUnit.MINUTES);
        mailService.sendValidationMail(flowerUser.getEmail(),code);
        return Result.success("验证码已发送至账户绑定邮箱"+flowerUser.getEmail()+"，请注意查收");
    }


    @Override
    public void checkRegisterInfo(FlowerUser flowerUser) {
        if (StringUtils.isEmpty(flowerUser.getLoginName())) {
            throw new MyException(ResultEnum.ERROR.getCode(), "注册时请传入用户名");
        }
        if (StringUtils.isEmpty(flowerUser.getPassword())) {
            throw new MyException(ResultEnum.ERROR.getCode(), "注册时请传入密码");
        }
        if (StringUtils.isEmpty(flowerUser.getEmail())) {
            throw new MyException(ResultEnum.ERROR.getCode(), "注册时请传入邮箱");
        }
        if (StringUtils.isEmpty(flowerUser.getCode())) {
            throw new MyException(ResultEnum.ERROR.getCode(), "请输入验证码");
        }
        FlowerUserExample flowerUserExample = new FlowerUserExample();
        flowerUserExample.createCriteria().andLoginNameEqualTo(flowerUser.getEmail());
        List<FlowerUser> loginNameList = flowerUserMapper.selectByExample(flowerUserExample);
        if (!CollectionUtils.isEmpty(loginNameList)) {
            throw new MyException(ResultEnum.ERROR.getCode(), "登录名已存在,请重新输入");
        }
        flowerUserExample.clear();
        flowerUserExample.createCriteria().andEmailEqualTo(flowerUser.getEmail());
        List<FlowerUser> emailList = flowerUserMapper.selectByExample(flowerUserExample);
        if (!CollectionUtils.isEmpty(emailList)) {
            throw new MyException(ResultEnum.ERROR.getCode(), "邮箱唯一哦");
        }
        String code = this.getRedisCode(flowerUser);
        if (!Objects.equals(code,flowerUser.getCode())) {
            throw new MyException(ResultEnum.ERROR.getCode(),"验证码输入错误,请检查");
        }
    }


    @Override
    public void createUser(FlowerUser flowerUser) throws Exception {
        FlowerCodeRule flowerCodeRule = new FlowerCodeRule();
        flowerCodeRule.setSize(MagicConstant.ONE);
        flowerCodeRule.setPlatId("");
        flowerCodeRule.setSeqTypeId(CodeRuleEnum.USER_ID.getCode());
        String userId = generatorCodeForMysql.GeneratorCode(flowerCodeRule);
        if (StringUtils.isEmpty(userId)) {
            throw new MyException(ResultEnum.ERROR.getCode(),"生成用户编号失败");
        }
        flowerUser.setUserId(userId);
        flowerUser.setUserType(MagicConstant.CUSTOMER);
        flowerUser.setPassword(Objects.equals(MagicConstant.DEFAULT_PWD,flowerUser.getPassword())
                ?MagicConstant.DEFAULT_PWD
                : MD5Util.md5(flowerUser.getPassword(),flowerUser.getUserId()));
        flowerUser.setUserStatus(MagicConstant.USER_LIVE);
        flowerUserMapper.insertSelective(flowerUser);
    }

    @Override
    public Result login(FlowerUser flowerUser) {
        try {
            this.checkLoginInfo(flowerUser);
        } catch (Exception e) {
            logger.error("checkLoginInfo:"+e.getMessage());
            return Result.error(ResultEnum.ERROR.getCode(), "参数校验未通过,请联系管理员");
        }
        return Result.success();
    }


    @Override
    public void checkLoginInfo(FlowerUser flowerUser) throws Exception {
        if (StringUtils.isEmpty(flowerUser.getLoginName()) || StringUtils.isEmpty(flowerUser.getPassword())) {
            throw new MyException(ResultEnum.ERROR.getCode(),"用户名或密码为空");
        }
        FlowerUserExample flowerUserExample = new FlowerUserExample();
        flowerUserExample.createCriteria()
                .andLoginNameEqualTo(flowerUser.getLoginName());
        List<FlowerUser> loginNameList = flowerUserMapper.selectByExample(flowerUserExample);
        if (CollectionUtils.isEmpty(loginNameList)) {
            throw new MyException(ResultEnum.ERROR.getCode(), "用户不存在");
        }
        String userId = loginNameList.get(0).getUserId();
        String dbPassword = loginNameList.get(0).getPassword();
        if (MagicConstant.DEFAULT_PWD.equals(flowerUser.getPassword())) {
            throw new MyException(ResultEnum.ERROR.getCode(), "该密码为默认密码,请修改");
        }
        if (!Objects.equals(dbPassword,MD5Util.md5(flowerUser.getPassword(),userId))) {
            throw new MyException(ResultEnum.ERROR.getCode(),"密码错误");
        }
    }

    @Override
    public Result forgetPassword(FlowerUser flowerUser) {
        if (StringUtils.isEmpty(flowerUser.getEmail())) {
            return Result.error(ResultEnum.ERROR.getCode(), "通过此功能重置密码,必须传入邮箱");
        }
        if (!Objects.equals(flowerUser.getCode(),this.getRedisCode(flowerUser))) {
            return Result.error(ResultEnum.ERROR.getCode(), "邮件验证码输入错误,请检查");
        }
        FlowerUserExample flowerUserExample = new FlowerUserExample();
        flowerUserExample.createCriteria().andEmailEqualTo(flowerUser.getEmail());
        List<FlowerUser> emailList = flowerUserMapper.selectByExample(flowerUserExample);
        if (CollectionUtils.isEmpty(emailList)) {
            return Result.error(ResultEnum.ERROR.getCode(), "账户不存在,请先注册");
        }
        try {
            flowerUser.setPassword(MD5Util.md5(flowerUser.getPassword(),emailList.get(0).getUserId()));
        } catch (Exception e) {
            logger.error("加密密码:"+e.getMessage());
            throw new MyException(ResultEnum.ERROR.getCode(),"密码加密异常");
        }
        flowerUserMapper.updateByExample(flowerUser,flowerUserExample);
        return Result.success();
    }

    @Override
    public String getRedisCode(FlowerUser flowerUser) {
        String code = "";
        try {
            code = (String) redisRepository.get(MagicConstant.getVerificationCode() + flowerUser.getEmail());
        } catch (Exception e) {
            logger.info(e.getMessage(), e);
            throw new MyException(ResultEnum.ERROR.getCode(), "验证码获取失败!");
        }
        if (!Objects.equals(code,flowerUser.getCode())) {
            throw new MyException(ResultEnum.ERROR.getCode(),"验证码输入错误,请检查");
        }
        return code;
    }

    @Override
    public Result updatePassword(FlowerUser flowerUser) {
        FlowerUserExample flowerUserExample = new FlowerUserExample();
        flowerUserExample.createCriteria().andUserIdEqualTo(flowerUser.getUserId());
        List<FlowerUser> userList = flowerUserMapper.selectByExample(flowerUserExample);
        if (!Objects.equals(flowerUser.getOldPassword(),userList.get(0).getPassword())) {
            return Result.error(ResultEnum.ERROR.getCode(), "老密码输入错误,请检查");
        }
        try {
            flowerUser.setPassword(MD5Util.md5(flowerUser.getPassword(),flowerUser.getUserId()));
        } catch (Exception e) {
            logger.error("加密密码:"+e.getMessage());
            throw new MyException(ResultEnum.ERROR.getCode(),"密码加密异常");
        }
        flowerUserMapper.updateByExample(flowerUser,flowerUserExample);
        return Result.success();
    }
}
